<template>
  <div class="app-container">
    <el-form ref="filterForm" :inline="true" :model="listQuery" class="filter-container">
      <el-form-item prop="createTime">
        <el-date-picker
          v-model="listQuery.createTime"
          type="date"
          size="small"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="listQuery.name" size="small" placeholder="推送标题" clearable style="width: 200px;" @keyup.enter.native="handleFilter" />
      </el-form-item>
      <el-form-item prop="templateType">
        <el-select v-model="listQuery.templateType" size="small" placeholder="请选择推送模板" filterable clearable @change="handleFilter">
          <el-option v-for="item in templateOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleFilter">筛选</el-button>
        <el-button size="small" @click="resetFilter">重置</el-button>
        <el-button
          size="small"
          type="success"
          icon="el-icon-plus"
          @click="toTweetNew"
        >新建推送</el-button>
        <!-- <el-divider direction="vertical" />
        <el-button
          size="small"
          icon="el-icon-download"
          :loading="exportTweetDetailsLoading"
          :disabled="exportTweetDetailsLoading"
          @click="exportTweetDetails"
        >推送明细导出</el-button> -->
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      stripe
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div class="table-expand-row">
            推送备注：{{ scope.row.remark }}
          </div>
          <div class="table-expand-row">
            模板消息链接：{{ scope.row.newsUrl }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="推送标题">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="推送模板" width="120" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.templateType === 1"
            effect="plain"
            size="mini"
          >会议上线提醒</el-tag>
          <el-tag
            v-if="scope.row.templateType === 2"
            effect="plain"
            size="mini"
          >会议开始提醒</el-tag>
          <el-tag
            v-if="scope.row.templateType === 3"
            effect="plain"
            size="mini"
          >会后调研推送</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | moment('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="已推送" width="80" align="center">
        <template slot-scope="scope">
          <i v-if="scope.row.state === 1" class="el-icon-check text-success" />
          <i v-if="scope.row.state === 0" class="el-icon-close text-warning" />
        </template>
      </el-table-column>
      <el-table-column label="已推送人数" width="120" align="center">
        <template slot-scope="scope">
          <span class="text-success">{{ scope.row.pushNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state === 0"
            size="mini"
            @click="toTweetEdit(scope.row.id)"
          >编辑任务</el-button>
          <!-- <el-popover
            v-if="scope.row.state === 1"
            width="300"
            trigger="click"
          >
            <el-row :gutter="10">
              <el-col :span="16">
                <el-date-picker
                  v-model="exportDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  size="small"
                  style="width: 100%;"
                />
              </el-col>
              <el-col :span="8">
                <el-button
                  icon="el-icon-download"
                  size="small"
                  plain
                  style="width: 100%;"
                  :disabled="exportTaskDataLoading"
                  @click="exportTaskData(scope.row.plantime)"
                >导出</el-button>
              </el-col>
            </el-row>

            <el-button
              slot="reference"
              type="success"
              size="mini"
              plain
              :loading="exportTaskDataLoading"
            >数据导出</el-button>
          </el-popover> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="fetchData" />

    <el-dialog
      title="文件正在生成中，请稍后到此链接下载文件"
      :visible.sync="showExportTweetDetailsLink"
      width="40%"
      center
    >
      <p class="text-center">{{ exportTweetDetailsLink }}</p>
      <div class="text-center mt30">
        <el-button
          type="success"
          plain
          @click="exportTweetDetailsLinkCopy(exportTweetDetailsLink, $event)"
        >复制下载地址</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTemplatesMsgs
} from '@/api/templatesMsgs'
import {
  exportTaskData,
  exportTweetDetails
} from '@/api/statements'
import Pagination from '@/components/Pagination'
import {
  blobExport,
  formatQuery
} from '@/utils'
import clip from '@/utils/clipboard'

export default {
  name: 'TweetsTemplateMsgsList',
  components: {
    Pagination
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        createTime: formatQuery(this.$route.query.createTime, false),
        name: formatQuery(this.$route.query.name, false),
        templateType: formatQuery(this.$route.query.templateType, true),
        page: 1,
        size: 30
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      templateOptions: [
        {
          name: '会议上线提醒',
          id: 1
        },
        {
          name: '会议开始提醒',
          id: 2
        },
        {
          name: '会后调研推送',
          id: 3
        }
      ],
      exportDate: '',
      exportTaskDataLoading: false,
      exportTweetDetailsLoading: false,
      showExportTweetDetailsLink: false,
      exportTweetDetailsLink: ''
    }
  },
  // watch: {
  //   $route: {
  //     handler(route) {
  //       if (!this._.isNil(route.query.page) &&
  //         !this._.isEmpty(route.query.page)
  //       ) {
  //         this.listQuery.page = parseInt(route.query.page)
  //       } else {
  //         this.listQuery.page = 1
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    if (!this._.isNil(this.$route.query.page) &&
      !this._.isEmpty(this.$route.query.page)
    ) {
      this.listQuery.page = parseInt(this.$route.query.page)
    } else {
      this.listQuery.page = 1
    }
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const query = {
        ...this.$route.query,
        ...this.listQuery
      }
      this.$router.push({
        query
      }).catch(err => {
        console.log(err)
      })
      getTemplatesMsgs(this.listQuery).then(response => {
        // console.log(response)
        const { data } = response
        // console.log(data)
        this.list = data
        this.total = response.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.fetchData()
    },
    resetFilter() {
      this.$refs.filterForm.resetFields()
      for (const i in this.listQuery) {
        if (i !== 'size') {
          this.listQuery[i] = undefined
        }
      }
      // console.log(this.listQuery)
      this.$router.push({
        query: {
          page: 1
        }
      }).catch(err => {
        console.log(err)
      })
      this.handleFilter()
    },
    exportTaskData(date) {
      const sendDate = this.$moment(date).format('YYYY-MM-DD')
      // console.log(sendDate)
      if (this._.isEmpty(this.exportDate)) {
        this.$message({
          type: 'warning',
          message: '请选择导出日期！'
        })
      } else {
        this.exportTaskDataLoading = true
        exportTaskData({
          sendDate,
          nowDate: this.exportDate
        }).then(response => {
          // console.log(response)
          blobExport(response, `微信图文数据 ${this.exportDate}.xlsx`)

          this.$message({
            type: 'success',
            message: '导出成功！',
            duration: 5000
          })
          this.exportDate = ''
          this.exportTaskDataLoading = false
        }).catch(err => {
          console.log(err)
          this.exportTaskDataLoading = false
        })
      }
    },
    exportTweetDetails() {
      // console.log(sendDate)
      if (this._.isEmpty(this.listQuery.createTime)) {
        this.$message({
          type: 'warning',
          message: '请选择发送日期！'
        })
      } else {
        this.exportTweetDetailsLoading = true
        exportTweetDetails({
          sendDate: this.listQuery.createTime
        }).then(response => {
          // console.log(response)
          // blobExport(response, `推送任务明细 ${this.listQuery.createTime}.xlsx`)

          this.exportTweetDetailsLink = response.msg
          this.showExportTweetDetailsLink = true
          this.exportTweetDetailsLoading = false
        }).catch(err => {
          console.log(err)
          this.exportTweetDetailsLoading = false
        })
      }
    },
    exportTweetDetailsLinkCopy(text, event) {
      clip(text, event)
    },
    toTweetNew() {
      this.$router.push('/template-msgs/new')
    },
    toTweetEdit(id) {
      this.$router.push(`/template-msgs/edit/${id}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.card-wrapper {
  .task-name {
    width: 300px;
    line-height: 1.5;
    margin: 0 auto;
    word-break: break-all;
  }
}
</style>
